# import json
# from pathlib import Path
#
# import pandas as pd
# import os
# import openpyxl
#
# def test(target,path,code_list,file_name):
#     text_file = open(str(path), "r", encoding="utf-8")
#     time_text = []
#     data_list = []
#     # code_data_list = []
#     data = {}
#     for line in text_file:
#         if target in line:
#             print(type(line))
#             # # 提取时间戳
#             timestamp = line.split()
#             print(timestamp)
#             # 提取参数部分
#             # 找到“参数：{”的起始位置
#             start_index = line.find('参数：') + len('参数：')
#             # 找到“}，返回值：”的结束位置
#             end_index = line.find('，返回值：', start_index)
#             parameters_str = line[start_index:end_index]
#             print(parameters_str)
#             # 将参数部分转换为字典
#             parameters = json.loads(parameters_str)
#             time_text.append(timestamp[0] + timestamp[1])
#             data["时间戳"] = time_text
#             for i in code_list:
#                 data[i]  = data_list.append(parameters[i])
#     df = pd.DataFrame(data)
#     root_dir  = os.path.dirname(os.path.abspath(__file__))
#     file_path = os.path.join(root_dir, str(file_name))
#     # 将DataFrame保存到Excel文件中
#     df.to_excel(file_path, index=False)
#
#
#
#
# if __name__ == '__main__':
#     #要查询的接口路径
#     target_word = '/terminal/order/add'
#     #要查询的字段
#     code_list = ['uniqueNo','code']
#     #要查询的文件夹
#     # 获取当前项目目录
#     project_directory = Path(__file__).parent
#     # 获取 data 文件夹的路径
#     data_directory = project_directory / 'data'
#     # 检查 data 文件夹是否存在
#     if data_directory.exists() and data_directory.is_dir():
#         # 遍历 data 文件夹中的每个文件
#         for file_path in data_directory.rglob('*'):
#             if file_path.is_file():
#                 file_name = file_path.name
#                 test(target_word,file_path,code_list,file_name)

import json
from pathlib import Path
import pandas as pd
import os


def read_log_file(file_path, target):
    data_list = []
    with open(file_path, "r", encoding="utf-8") as text_file:
        for line in text_file:
            if target in line:
                timestamp, parameters_str = parse_log_line(line)
                print(timestamp)
                time_data = timestamp[0]+timestamp[1]
                parameters = json.loads(parameters_str)
                data_list.append({"时间戳": time_data, **parameters})
    return data_list


def parse_log_line(line):
    # 假设日志行的格式是已知的，并且符合以下结构：
    # [时间戳] ... 参数：{...}，返回值：...
    timestamp = line.split()  # 提取时间戳，假设它是行的第一个元素
    start_index = line.find('参数：') + len('参数：')
    end_index = line.find('，返回值：', start_index)
    parameters_str = line[start_index:end_index]
    return timestamp, parameters_str


def save_to_excel(data_list, file_path):
    df = pd.DataFrame(data_list)
    df.to_excel(file_path, index=False)


def main():
    target_word = '/terminal/order/add'
    code_list = ['uniqueNo', 'code','deviceId']  # 这些字段应该在日志文件的参数部分中
    project_directory = Path(__file__).parent
    data_directory = project_directory / 'data'

    if data_directory.exists() and data_directory.is_dir():
        all_data = []
        for file_path in data_directory.rglob('*'):
            if file_path.is_file():
                file_data = read_log_file(file_path, target_word)
                # 过滤只包含code_list中字段的数据
                filtered_data = [{k: v for k, v in item.items() if k in code_list or k == "时间戳"} for item in
                                 file_data]
        # all_data.extend(filtered_data)
                root_dir = os.path.dirname(os.path.abspath(__file__))
                file_name = file_path.name[:-4]
                output_file_path = os.path.join(root_dir, file_name+'.xlsx')
                save_to_excel(filtered_data, output_file_path)




if __name__ == '__main__':
    main()
